import requests
from bs4 import BeautifulSoup
import openpyxl

def html_get():
    header = {
        'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) '
                      'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Mobile Safari/537.36'
    }
    global lst
    lst = [['编号', '名称', '推荐语', '评分', '链接地址']]

    for i in range(10):  # 一共 10 页，每页 25 条
        url = f'https://movie.douban.com/top250?start={i * 25}&filter='
        resp = requests.get(url, headers=header)
        bs = BeautifulSoup(resp.text, 'html.parser')

        grid_view = bs.find('ol', class_='grid_view')
        all_li = grid_view.find_all('li')

        for item in all_li:
            no = item.find('em').text
            title = item.find('span', class_='title').text
            inq = item.find('span', class_='inq')
            inq = inq.text if inq else '无推荐语'
            rat = item.find('span', class_='rating_num').text
            url_films = item.find('a')['href']

            print(no, title, inq, rat, url_films)
            lst.append([no, title, inq, rat, url_films])

def file_storage():
    wb = openpyxl.Workbook()
    sheet = wb.active
    sheet.title = 'filmsTop250'

    for item in lst:
        sheet.append(item)

    wb.save('films.xlsx')

if __name__ == '__main__':
    html_get()
    file_storage()
